package com.atguigu.gulimail.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimail.product.dao.CategoryDao;
import com.atguigu.gulimail.product.entity.CategoryEntity;
import com.atguigu.gulimail.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listForTree() {
        //这里的baseMapper 就是categoryDao
        //查出所有的分类
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        //使用stream api 查出所有的一级分类
        List<CategoryEntity> rootMenus = categoryEntities.stream().filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                .map(menu->{
                    menu.setChildrens(getChildrens(menu,categoryEntities));
                    return menu;
                }).sorted((menu1,menu2)->{
                    return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
                }).collect(Collectors.toList());
        return rootMenus;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {

    }

    private List<CategoryEntity> getChildrens(CategoryEntity root,List<CategoryEntity> all){

        //递归
        //首先 将所有的数据集合  遍历 过滤 其中 父id = 根id的数据

        List<CategoryEntity> list = all.stream().filter(categoryEntity -> categoryEntity.getParentCid()== root.getCatId())
                .map(menu -> {
                    menu.setChildrens(getChildrens(menu, all));
                    return menu;
                }).sorted((menu1, menu2) -> {
                    return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
                }).collect(Collectors.toList());

        return list;
    }

}